package com.boyon.system.service;

import java.util.List;

import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import com.boyon.common.exection.BusinessException;
import com.boyon.common.log.annotation.MethodFlag;
import com.boyon.common.status.StatusType;
import com.boyon.common.tools.ObjectTool;
import com.boyon.hbm.criteria.OperationType;
import com.boyon.hbm.criteria.Param;
import com.boyon.hbm.criteria.Query;
import com.boyon.service.AbstractService;
import com.boyon.system.entity.Coding;

/**
 * ClassName:CodingService <br/>
 * Function: 系统编码设置业务处理类. <br/>
 * Date: 2018年3月14日 下午9:56:25 <br/>
 * 
 * @author sunshulin
 * @version
 * @since JDK 1.8
 * @see
 */
@Service
public class CodingService extends AbstractService {

	
	
	/**
	 * 
	 * updateCoding:更新编码规则. <br/>
	 * 
	 * @author sunshulin
	 * @param coding
	 * @since JDK 1.8
	 */
	@MethodFlag(key = "10000004")
	@Transactional
	public Long updateCoding(Coding coding) {
		Coding entity = findByCodingId(coding.getCodingId());
		if (entity.getStatus() == StatusType.start.getStatus()) {
			throw BusinessException.builder(0, "编码规则已启用不能修改");
		}
		ObjectTool.copy(coding, entity, new String[] { "status", "codingId",
				"codingName", "codingKey" });
		generalDao.saveOrUpdate(entity);
		return entity.getCodingId();
	}

	/**
	 * 
	 * start:启用编码规则. <br/>
	 * 
	 * @author sunshulin
	 * @param codingId
	 * @return
	 * @since JDK 1.8
	 */
	@MethodFlag(key = "10000004")
	@Transactional
	public Long start(Long codingId) {
		Coding entity = findByCodingId(codingId);
		if (entity.getStatus() == StatusType.start.getStatus()) {
			throw BusinessException.builder(0, "系统编码已启用");
		}
		entity.setStatus(StatusType.start.getStatus());
		generalDao.saveOrUpdate(entity);
		return entity.getCodingId();
	}

	/**
	 * 
	 * findByCodingId:查找编码. <br/>
	 * 
	 * @author sunshulin
	 * @param codeId
	 * @return
	 * @since JDK 1.8
	 */
	@Transactional(readOnly = true)
	public Coding findByCodingId(Long codeId) {
		Coding entity = generalDao.get(Coding.class, codeId);
		if (entity == null) {
			throw BusinessException.builder(0, "编码规则不存在");
		}
		return entity;
	}

	/**
	 * 
	 * query:查询编码规则列表 <br/>
	 * 
	 * @author sunshulin
	 * @param query
	 * @return
	 * @since JDK 1.8
	 */
	@Transactional(readOnly = true)
	public List<Coding> query(Query query) {
		List<Coding> list = generalDao.query(Coding.class, query);
		return list;
	}

	/**
	 * 
	 * query:查询编码规则列表 <br/>
	 * 
	 * @author sunshulin
	 * @param query
	 * @return
	 * @since JDK 1.8
	 */
	@Transactional(readOnly = true)
	public Coding findByCodingKey(String codingKey) {
		Query query = new Query();
		query.addParam(
				new Param<String>("codingKey", OperationType.eq, codingKey));
		Coding entity = generalDao.sign(Coding.class, query);
		if (entity == null) {
			throw BusinessException.builder(0, "编码规则不存在");
		}
		return entity;
	}
}
